// 游戏设置系统 - 完整功能实现
class GameSettings {
    constructor() {
        this.settings = {
            textSpeed: 3,
            soundEnabled: true,
            autoSave: true,
            highContrast: false,
            reducedMotion: false,
            fontSize: 'medium'
        };
        
        this.loadSettings();
        this.init();
    }

    init() {
        this.bindSettingsEvents();
        this.applySettings();
        console.log('⚙️ 游戏设置系统已加载');
    }

    bindSettingsEvents() {
        // 文字速度调节
        const textSpeedSlider = document.getElementById('textSpeed');
        const textSpeedValue = document.getElementById('textSpeedValue');
        
        if (textSpeedSlider && textSpeedValue) {
            textSpeedSlider.addEventListener('input', (e) => {
                const value = parseInt(e.target.value);
                this.settings.textSpeed = value;
                textSpeedValue.textContent = value;
                this.saveSettings();
                this.applyTextSpeed();
            });
        }

        // 音效开关
        const soundEnabled = document.getElementById('soundEnabled');
        if (soundEnabled) {
            soundEnabled.addEventListener('change', (e) => {
                this.settings.soundEnabled = e.target.checked;
                this.saveSettings();
                this.applySoundSettings();
            });
        }

        // 自动保存开关
        const autoSave = document.getElementById('autoSave');
        if (autoSave) {
            autoSave.addEventListener('change', (e) => {
                this.settings.autoSave = e.target.checked;
                this.saveSettings();
                this.showNotification(e.target.checked ? '自动保存已开启' : '自动保存已关闭');
            });
        }

        // 高对比度模式
        const highContrast = document.getElementById('highContrast');
        if (highContrast) {
            highContrast.addEventListener('change', (e) => {
                this.settings.highContrast = e.target.checked;
                this.saveSettings();
                this.applyHighContrast();
            });
        }

        // 减少动画
        const reducedMotion = document.getElementById('reducedMotion');
        if (reducedMotion) {
            reducedMotion.addEventListener('change', (e) => {
                this.settings.reducedMotion = e.target.checked;
                this.saveSettings();
                this.applyReducedMotion();
            });
        }

        // 字体大小
        const fontSize = document.getElementById('fontSize');
        if (fontSize) {
            fontSize.addEventListener('change', (e) => {
                this.settings.fontSize = e.target.value;
                this.saveSettings();
                this.applyFontSize();
            });
        }

        // 导出存档
        const exportSaveBtn = document.getElementById('exportSaveBtn');
        if (exportSaveBtn) {
            exportSaveBtn.addEventListener('click', () => {
                this.exportSaveData();
            });
        }

        // 导入存档
        const importSaveBtn = document.getElementById('importSaveBtn');
        if (importSaveBtn) {
            importSaveBtn.addEventListener('click', () => {
                this.importSaveData();
            });
        }

        // 重置游戏
        const resetGameBtn = document.getElementById('resetGameBtn');
        if (resetGameBtn) {
            resetGameBtn.addEventListener('click', () => {
                this.resetGame();
            });
        }
    }

    // 应用文字速度设置
    applyTextSpeed() {
        const speeds = {
            1: 100,  // 很慢
            2: 75,   // 慢
            3: 50,   // 正常
            4: 25,   // 快
            5: 10    // 很快
        };
        
        const speed = speeds[this.settings.textSpeed] || 50;
        document.documentElement.style.setProperty('--text-animation-duration', `${speed}ms`);
        
        // 如果有打字机效果，应用速度
        if (window.uiManager && window.uiManager.typewriter) {
            window.uiManager.typewriter.speed = speed;
        }
    }

    // 应用音效设置
    applySoundSettings() {
        const enabled = this.settings.soundEnabled;
        
        // 设置全局音效状态
        if (window.audioManager) {
            window.audioManager.setEnabled(enabled);
        }
        
        // 静音/取消静音所有音频元素
        const audioElements = document.querySelectorAll('audio');
        audioElements.forEach(audio => {
            audio.muted = !enabled;
        });
        
        this.showNotification(enabled ? '音效已开启' : '音效已关闭');
    }

    // 应用高对比度模式
    applyHighContrast() {
        const enabled = this.settings.highContrast;
        
        if (enabled) {
            document.documentElement.classList.add('high-contrast');
            // 添加高对比度CSS变量
            document.documentElement.style.setProperty('--primary-color', '#ffffff');
            document.documentElement.style.setProperty('--bg-dark', '#000000');
            document.documentElement.style.setProperty('--text-primary', '#ffffff');
            document.documentElement.style.setProperty('--text-secondary', '#cccccc');
        } else {
            document.documentElement.classList.remove('high-contrast');
            // 恢复原始颜色
            document.documentElement.style.setProperty('--primary-color', '#00d4ff');
            document.documentElement.style.setProperty('--bg-dark', '#0a0e1a');
            document.documentElement.style.setProperty('--text-primary', '#ffffff');
            document.documentElement.style.setProperty('--text-secondary', '#b8c5d1');
        }
        
        this.showNotification(enabled ? '高对比度模式已开启' : '高对比度模式已关闭');
    }

    // 应用减少动画设置
    applyReducedMotion() {
        const enabled = this.settings.reducedMotion;
        
        if (enabled) {
            document.documentElement.classList.add('reduced-motion');
            // 禁用动画
            const style = document.createElement('style');
            style.id = 'reduced-motion-style';
            style.textContent = `
                *, *::before, *::after {
                    animation-duration: 0.01ms !important;
                    animation-iteration-count: 1 !important;
                    transition-duration: 0.01ms !important;
                    scroll-behavior: auto !important;
                }
            `;
            document.head.appendChild(style);
        } else {
            document.documentElement.classList.remove('reduced-motion');
            const style = document.getElementById('reduced-motion-style');
            if (style) {
                style.remove();
            }
        }
        
        this.showNotification(enabled ? '动画已减少' : '动画已恢复');
    }

    // 应用字体大小设置
    applyFontSize() {
        const sizes = {
            'small': '0.875',
            'medium': '1',
            'large': '1.125',
            'xlarge': '1.25'
        };
        
        const scale = sizes[this.settings.fontSize] || '1';
        document.documentElement.style.setProperty('--font-scale', scale);
        
        // 应用到所有文本元素
        const textElements = document.querySelectorAll('p, span, div, button, input, label');
        textElements.forEach(element => {
            element.style.fontSize = `calc(var(--font-size-base) * ${scale})`;
        });
        
        this.showNotification(`字体大小已调整为：${this.settings.fontSize}`);
    }

    // 导出存档数据
    exportSaveData() {
        console.log('开始导出存档...');
        
        // 询问用户是否同意导出
        const confirmed = confirm('是否同意导出存档数据到本地文件？\n\n这将下载一个包含您游戏进度的加密文件。');
        
        if (!confirmed) {
            this.showNotification('导出操作已取消');
            return;
        }

        try {
            // 收集所有游戏数据，处理可能的null值
            const gameData = {
                settings: this.settings || {},
                gameState: this.safeGetGameState(),
                achievements: this.safeGetAchievements(),
                characterData: this.safeGetCharacterData(),
                storyProgress: this.safeGetStoryProgress(),
                playerStats: this.safeGetPlayerStats(),
                timestamp: Date.now(),
                version: '1.0.0',
                exportId: this.generateExportId()
            };

            console.log('收集的游戏数据:', gameData);

            // 生成加密存档数据（改进的加密算法）
            const encryptedData = this.encryptSaveData(gameData);
            
            console.log('加密数据长度:', encryptedData.length);
            
            // 创建文件并下载（改进的下载机制）
            this.downloadFile(encryptedData);

        } catch (error) {
            console.error('导出存档失败:', error);
            this.showNotification(`导出存档失败：${error.message}`, 'error');
        }
    }

    // 安全获取游戏状态
    safeGetGameState() {
        try {
            if (window.gameEngine && typeof window.gameEngine.getGameState === 'function') {
                return window.gameEngine.getGameState() || {};
            }
            return {
                currentScene: 'main_menu',
                chapter: 1,
                lastSaveTime: Date.now()
            };
        } catch (error) {
            console.warn('获取游戏状态失败:', error);
            return { error: 'failed_to_get_game_state' };
        }
    }

    // 安全获取成就数据
    safeGetAchievements() {
        try {
            if (window.achievementSystem && typeof window.achievementSystem.getUnlockedAchievements === 'function') {
                return window.achievementSystem.getUnlockedAchievements() || [];
            }
            return [];
        } catch (error) {
            console.warn('获取成就数据失败:', error);
            return [];
        }
    }

    // 安全获取角色数据
    safeGetCharacterData() {
        try {
            if (window.characterSystem && typeof window.characterSystem.getCharacterData === 'function') {
                return window.characterSystem.getCharacterData() || {};
            }
            return {
                attributes: {
                    scientific: 50,
                    courage: 50,
                    caution: 50,
                    empathy: 50
                }
            };
        } catch (error) {
            console.warn('获取角色数据失败:', error);
            return { error: 'failed_to_get_character_data' };
        }
    }

    // 安全获取故事进度
    safeGetStoryProgress() {
        try {
            if (window.storyManager && typeof window.storyManager.getProgress === 'function') {
                return window.storyManager.getProgress() || {};
            }
            return {
                currentChapter: 1,
                completedScenes: [],
                totalPlayTime: 0
            };
        } catch (error) {
            console.warn('获取故事进度失败:', error);
            return { error: 'failed_to_get_story_progress' };
        }
    }

    // 安全获取玩家统计数据
    safeGetPlayerStats() {
        try {
            return {
                totalChoices: localStorage.getItem('timeEcho_totalChoices') || '0',
                totalPlayTime: localStorage.getItem('timeEcho_totalPlayTime') || '0',
                gamesCompleted: localStorage.getItem('timeEcho_gamesCompleted') || '0',
                favoriteEnding: localStorage.getItem('timeEcho_favoriteEnding') || 'unknown'
            };
        } catch (error) {
            console.warn('获取玩家统计失败:', error);
            return {};
        }
    }

    // 生成导出ID
    generateExportId() {
        return 'TE_' + Date.now().toString(36) + '_' + Math.random().toString(36).substr(2, 9);
    }

    // 改进的文件下载方法
    downloadFile(encryptedData) {
        try {
            const fileName = `TimeEcho_Save_${new Date().toISOString().slice(0, 10)}_${new Date().getHours()}${new Date().getMinutes()}.txt`;
            
            // 方法1: 使用Blob和URL.createObjectURL
            if (window.Blob && window.URL && window.URL.createObjectURL) {
                const blob = new Blob([encryptedData], { 
                    type: 'text/plain;charset=utf-8' 
                });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                a.style.display = 'none';
                
                // 确保添加到DOM中
                document.body.appendChild(a);
                
                // 模拟点击
                a.click();
                
                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }, 100);
                
                this.showNotification('存档已成功导出到本地文件');
                console.log('存档导出成功，文件名:', fileName);
                return;
            }
            
            // 方法2: 使用data URI (备用方案)
            const dataUri = 'data:text/plain;charset=utf-8,' + encodeURIComponent(encryptedData);
            const a = document.createElement('a');
            a.href = dataUri;
            a.download = fileName;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            
            this.showNotification('存档已成功导出到本地文件');
            console.log('存档导出成功（备用方案），文件名:', fileName);
            
        } catch (error) {
            console.error('文件下载失败:', error);
            // 如果下载失败，显示数据给用户手动复制
            this.showDataForManualCopy(encryptedData);
        }
    }

    // 显示数据供用户手动复制
    showDataForManualCopy(encryptedData) {
        const modalHtml = `
            <div id="manualCopyModal" style="
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.8);
                z-index: 10001;
                display: flex;
                align-items: center;
                justify-content: center;
            ">
                <div style="
                    background: #1a1f2e;
                    border: 1px solid #00d4ff;
                    border-radius: 12px;
                    padding: 20px;
                    max-width: 600px;
                    max-height: 80%;
                    overflow-y: auto;
                    color: white;
                ">
                    <h3 style="color: #00d4ff; margin-bottom: 15px;">手动保存存档数据</h3>
                    <p style="margin-bottom: 15px;">自动下载失败，请手动复制以下数据并保存为txt文件：</p>
                    <textarea id="saveDataText" readonly style="
                        width: 100%;
                        height: 200px;
                        background: #0a0e1a;
                        color: #ffffff;
                        border: 1px solid #00d4ff;
                        border-radius: 4px;
                        padding: 10px;
                        font-family: monospace;
                        font-size: 12px;
                        resize: vertical;
                    ">${encryptedData}</textarea>
                    <div style="margin-top: 15px; text-align: center;">
                        <button id="copyDataBtn" style="
                            background: #00d4ff;
                            border: none;
                            color: #0a0e1a;
                            padding: 8px 16px;
                            border-radius: 4px;
                            margin-right: 10px;
                            cursor: pointer;
                        ">复制数据</button>
                        <button id="closeModalBtn" style="
                            background: #ff6b6b;
                            border: none;
                            color: white;
                            padding: 8px 16px;
                            border-radius: 4px;
                            cursor: pointer;
                        ">关闭</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 绑定事件
        document.getElementById('copyDataBtn').onclick = () => {
            const textarea = document.getElementById('saveDataText');
            textarea.select();
            try {
                document.execCommand('copy');
                this.showNotification('数据已复制到剪贴板');
            } catch (error) {
                console.error('复制失败:', error);
                this.showNotification('复制失败，请手动选择并复制', 'error');
            }
        };
        
        document.getElementById('closeModalBtn').onclick = () => {
            const modal = document.getElementById('manualCopyModal');
            if (modal) {
                modal.remove();
            }
        };
    }

    // 导入存档数据
    // 导入存档数据（改进版本）
    importSaveData() {
        console.log('开始导入存档...');
        
        // 创建文件选择器
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.txt';
        
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (!file) {
                console.log('没有选择文件');
                return;
            }

            console.log('选择的文件:', file.name, '大小:', file.size);
            
            const reader = new FileReader();
            reader.onload = (event) => {
                try {
                    console.log('文件读取完成');
                    
                    // 获取文件内容
                    const encryptedData = event.target.result;
                    console.log('读取到的数据长度:', encryptedData.length);
                    console.log('数据预览:', encryptedData.substring(0, 100) + '...');
                    
                    // 验证文件格式
                    if (!this.validateFileFormat(encryptedData)) {
                        throw new Error('无效的存档文件格式，请确保选择正确的txt存档文件');
                    }
                    
                    // 解密存档数据
                    const gameData = this.decryptSaveData(encryptedData);
                    console.log('解密后的数据:', gameData);
                    
                    // 验证数据完整性
                    if (!this.validateSaveData(gameData)) {
                        throw new Error('存档文件已损坏或数据不完整');
                    }

                    // 显示存档信息并确认导入
                    const importInfo = this.buildImportConfirmation(gameData);
                    const confirmed = confirm(importInfo);
                    
                    if (!confirmed) {
                        this.showNotification('导入操作已取消');
                        return;
                    }

                    // 应用存档数据
                    this.applySaveData(gameData);
                    this.showNotification('存档导入成功！游戏数据已恢复');
                    
                    console.log('存档导入完成');
                    
                    // 刷新界面
                    setTimeout(() => {
                        if (window.uiManager && typeof window.uiManager.refreshUI === 'function') {
                            window.uiManager.refreshUI();
                        }
                        // 返回主菜单以显示更新后的数据
                        const screens = document.querySelectorAll('.screen');
                        screens.forEach(screen => screen.classList.remove('active'));
                        const mainMenu = document.getElementById('mainMenu');
                        if (mainMenu) {
                            mainMenu.classList.add('active');
                        }
                    }, 500);
                    
                } catch (error) {
                    console.error('导入存档失败:', error);
                    this.showDetailedImportError(error, event.target.result);
                }
            };
            
            reader.onerror = () => {
                console.error('文件读取失败');
                this.showNotification('文件读取失败，请重试', 'error');
            };
            
            reader.readAsText(file, 'utf-8');
        };
        
        input.click();
    }
    
    // 验证文件格式
    validateFileFormat(data) {
        if (typeof data !== 'string') {
            console.error('文件内容不是字符串');
            return false;
        }
        
        const lines = data.trim().split('\n');
        
        if (lines.length < 4) {
            console.error('文件行数不足:', lines.length);
            return false;
        }
        
        if (!lines[0].startsWith('TimeEcho_SaveData_')) {
            console.error('文件头不匹配:', lines[0]);
            return false;
        }
        
        // 检查元数据是否为有效JSON
        try {
            JSON.parse(lines[1]);
        } catch (e) {
            console.error('元数据JSON无效:', lines[1]);
            return false;
        }
        
        return true;
    }
    
    // 构建导入确认信息
    buildImportConfirmation(gameData) {
        const timestamp = gameData.timestamp ? new Date(gameData.timestamp).toLocaleString() : '未知';
        const version = gameData.version || '未知';
        const exportId = gameData.exportId || '未知';
        
        let info = `检测到存档数据：\n\n`;
        info += `保存时间: ${timestamp}\n`;
        info += `游戏版本: ${version}\n`;
        info += `导出ID: ${exportId}\n\n`;
        
        // 显示存档包含的数据
        const dataTypes = [];
        if (gameData.settings) dataTypes.push('游戏设置');
        if (gameData.gameState) dataTypes.push('游戏状态');
        if (gameData.achievements && gameData.achievements.length > 0) dataTypes.push(`成就数据(${gameData.achievements.length}项)`);
        if (gameData.characterData) dataTypes.push('角色数据');
        if (gameData.storyProgress) dataTypes.push('故事进度');
        if (gameData.playerStats) dataTypes.push('玩家统计');
        
        if (dataTypes.length > 0) {
            info += `包含数据: ${dataTypes.join(', ')}\n\n`;
        }
        
        info += `是否导入此存档？当前进度将被覆盖。`;
        
        return info;
    }
    
    // 显示详细的导入错误信息
    showDetailedImportError(error, rawData) {
        let errorMsg = '导入存档失败：' + error.message;
        
        // 分析具体错误原因
        if (error.message.includes('无效的存档文件格式')) {
            errorMsg += '\n\n可能原因：\n• 选择了错误的文件\n• 文件已损坏\n• 文件不是游戏导出的存档';
        } else if (error.message.includes('校验失败')) {
            errorMsg += '\n\n可能原因：\n• 文件在传输过程中损坏\n• 文件被意外修改\n• 存档版本不兼容';
        } else if (error.message.includes('解密失败')) {
            errorMsg += '\n\n可能原因：\n• 存档文件损坏\n• 加密密钥不匹配\n• 文件格式错误';
        }
        
        // 显示错误对话框
        this.showNotification(errorMsg, 'error');
        
        // 提供手动修复选项
        if (rawData && rawData.length > 0) {
            setTimeout(() => {
                const showDebugInfo = confirm('是否显示调试信息？这可能有助于诊断问题。');
                if (showDebugInfo) {
                    this.showDebugModal(error, rawData);
                }
            }, 2000);
        }
    }
    
    // 显示调试信息
    showDebugModal(error, rawData) {
        const debugHtml = `
            <div id="debugModal" style="
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.8);
                z-index: 10001;
                display: flex;
                align-items: center;
                justify-content: center;
            ">
                <div style="
                    background: #1a1f2e;
                    border: 1px solid #ff6b6b;
                    border-radius: 12px;
                    padding: 20px;
                    max-width: 700px;
                    max-height: 80%;
                    overflow-y: auto;
                    color: white;
                ">
                    <h3 style="color: #ff6b6b; margin-bottom: 15px;">导入失败调试信息</h3>
                    <div style="margin-bottom: 15px;">
                        <strong>错误信息:</strong><br>
                        <span style="color: #ff6b6b;">${error.message}</span>
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>文件内容预览 (前500字符):</strong><br>
                        <textarea readonly style="
                            width: 100%;
                            height: 120px;
                            background: #0a0e1a;
                            color: #ffffff;
                            border: 1px solid #ff6b6b;
                            border-radius: 4px;
                            padding: 10px;
                            font-family: monospace;
                            font-size: 12px;
                        ">${rawData.substring(0, 500)}${rawData.length > 500 ? '...' : ''}</textarea>
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>文件信息:</strong><br>
                        长度: ${rawData.length} 字符<br>
                        行数: ${rawData.split('\n').length} 行
                    </div>
                    <div style="text-align: center;">
                        <button id="closeDebugBtn" style="
                            background: #ff6b6b;
                            border: none;
                            color: white;
                            padding: 8px 16px;
                            border-radius: 4px;
                            cursor: pointer;
                        ">关闭</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', debugHtml);
        
        document.getElementById('closeDebugBtn').onclick = () => {
            const modal = document.getElementById('debugModal');
            if (modal) {
                modal.remove();
            }
        };
    }

    // 加密存档数据（修复后的加密算法）
    encryptSaveData(data) {
        try {
            console.log('开始加密存档数据...');
            
            const jsonString = JSON.stringify(data, null, 0);
            console.log('JSON字符串长度:', jsonString.length);
            console.log('JSON开头:', jsonString.substring(0, 50));
            
            // 使用与解密一致的加密方法
            let encrypted = '';
            const key = 'TimeEcho2024'; // 固定密钥
            
            console.log('开始加密过程...');
            
            // XOR加密 + 字符映射
            for (let i = 0; i < jsonString.length; i++) {
                const originalCharCode = jsonString.charCodeAt(i);
                const keyChar = key.charCodeAt(i % key.length);
                
                // XOR加密
                const encryptedCharCode = originalCharCode ^ keyChar;
                
                // 字符映射：将结果映射到安全的可打印ASCII范围(33-126)
                const safeCharCode = (encryptedCharCode % 94) + 33;
                
                encrypted += String.fromCharCode(safeCharCode);
            }
            
            console.log('加密完成，加密字符串长度:', encrypted.length);
            console.log('加密字符串开头:', encrypted.substring(0, 50));
            
            // 使用安全的Base64编码
            let base64;
            try {
                base64 = btoa(encrypted);
                console.log('Base64编码成功，长度:', base64.length);
            } catch (e) {
                console.warn('btoa失败，使用备用编码方法:', e);
                // 备用编码方法
                base64 = this.safeBase64Encode(encrypted);
                console.log('备用Base64编码成功，长度:', base64.length);
            }
            
            // 生成文件头和校验信息
            const header = 'TimeEcho_SaveData_V1.0';
            const checksum = this.calculateChecksum(base64);
            const metadata = {
                length: jsonString.length,
                timestamp: Date.now(),
                version: '1.0.0',
                encryptionMethod: 'XOR+CharMap+Base64'
            };
            
            const result = [
                header,
                JSON.stringify(metadata),
                base64,
                checksum
            ].join('\n');
            
            console.log('最终加密数据长度:', result.length);
            return result;
            
        } catch (error) {
            console.error('加密过程中出错:', error);
            throw new Error('数据加密失败: ' + error.message);
        }
    }

    // 安全的Base64编码（备用方法）
    safeBase64Encode(str) {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
        let result = '';
        let i = 0;
        
        while (i < str.length) {
            const a = str.charCodeAt(i++);
            const b = i < str.length ? str.charCodeAt(i++) : 0;
            const c = i < str.length ? str.charCodeAt(i++) : 0;
            
            const bitmap = (a << 16) | (b << 8) | c;
            
            result += chars.charAt((bitmap >> 18) & 63);
            result += chars.charAt((bitmap >> 12) & 63);
            result += i - 2 < str.length ? chars.charAt((bitmap >> 6) & 63) : '=';
            result += i - 1 < str.length ? chars.charAt(bitmap & 63) : '=';
        }
        
        return result;
    }

    // 解密存档数据（完全修复版本）
    decryptSaveData(encryptedData) {
        try {
            console.log('开始解密存档数据...');
            
            const lines = encryptedData.trim().split('\n');
            console.log('解析到', lines.length, '行数据');
            
            if (lines.length < 4 || !lines[0].startsWith('TimeEcho_SaveData_')) {
                throw new Error('无效的存档文件格式');
            }
            
            const header = lines[0];
            const metadataStr = lines[1];
            const base64Data = lines[2];
            const checksum = lines[3];
            
            console.log('文件头:', header);
            console.log('Base64数据长度:', base64Data.length);
            console.log('校验和:', checksum);
            
            // 解析元数据
            let metadata;
            try {
                metadata = JSON.parse(metadataStr);
                console.log('存档元数据:', metadata);
            } catch (e) {
                throw new Error('存档元数据解析失败');
            }
            
            // 验证校验和
            const calculatedChecksum = this.calculateChecksum(base64Data);
            console.log('计算的校验和:', calculatedChecksum);
            console.log('存档校验和:', checksum);
            
            if (calculatedChecksum !== checksum) {
                throw new Error('存档文件校验失败，可能已损坏');
            }
            
            // 解码Base64
            let decoded;
            try {
                console.log('尝试使用atob解码...');
                // 修复Base64解码问题
                const cleanBase64 = base64Data.replace(/[^A-Za-z0-9+\/=]/g, '');
                decoded = atob(cleanBase64);
                console.log('Base64解码成功，解码数据长度:', decoded.length);
            } catch (e) {
                console.warn('atob失败，使用备用解码方法:', e);
                try {
                    decoded = this.safeBase64Decode(base64Data);
                    console.log('备用解码成功，解码数据长度:', decoded.length);
                } catch (e2) {
                    throw new Error('Base64解码失败: ' + e2.message);
                }
            }
            
            // 解密（完全修复的算法）
            let original = '';
            const key = 'TimeEcho2024';
            
            console.log('开始解密，已解码数据长度:', decoded.length);
            
            for (let i = 0; i < decoded.length; i++) {
                const encryptedCharCode = decoded.charCodeAt(i);
                
                // 反向字符映射：将安全字符范围映射回原始范围
                let mappedCharCode;
                if (encryptedCharCode >= 33 && encryptedCharCode <= 126) {
                    // 将安全字符(33-126)映射回原始编码范围(0-93)
                    mappedCharCode = encryptedCharCode - 33;
                } else {
                    // 超出范围的字符直接使用
                    mappedCharCode = encryptedCharCode;
                }
                
                // XOR解密：使用密钥进行异或解密
                const keyChar = key.charCodeAt(i % key.length);
                const originalCharCode = mappedCharCode ^ keyChar;
                
                // 确保字符在有效范围内
                if (originalCharCode >= 0 && originalCharCode <= 1114111) {
                    original += String.fromCharCode(originalCharCode);
                } else {
                    console.warn(`无效字符码在位置 ${i}: ${originalCharCode}`);
                    // 跳过无效字符或使用替代字符
                    original += '?';
                }
            }
            
            console.log('解密完成，原始数据长度:', original.length);
            console.log('原始数据开头:', original.substring(0, 50));
            console.log('原始数据结尾:', original.substring(original.length - 50));
            
            // 清理可能的非JSON字符
            let cleanJson = original.trim();
            
            // 尝试修复常见的JSON问题
            if (!cleanJson.startsWith('{')) {
                // 寻找第一个 { 字符
                const startIndex = cleanJson.indexOf('{');
                if (startIndex > 0) {
                    cleanJson = cleanJson.substring(startIndex);
                    console.log('修正JSON开始位置，新长度:', cleanJson.length);
                }
            }
            
            if (!cleanJson.endsWith('}')) {
                // 寻找最后一个 } 字符
                const endIndex = cleanJson.lastIndexOf('}');
                if (endIndex >= 0) {
                    cleanJson = cleanJson.substring(0, endIndex + 1);
                    console.log('修正JSON结束位置，新长度:', cleanJson.length);
                }
            }
            
            console.log('清理后的JSON开头:', cleanJson.substring(0, 100));
            
            // 解析JSON
            let result;
            try {
                result = JSON.parse(cleanJson);
                console.log('JSON解析成功，游戏数据解析完成');
            } catch (e) {
                console.error('JSON解析失败:', e);
                console.error('清理后的数据:', cleanJson.substring(0, 200));
                
                // 尝试更激进的修复
                try {
                    // 移除所有不可见字符和控制字符
                    const ultraClean = cleanJson.replace(/[\x00-\x1F\x7F-\x9F]/g, '');
                    console.log('超级清理后尝试解析...');
                    result = JSON.parse(ultraClean);
                    console.log('超级清理后JSON解析成功');
                } catch (e2) {
                    // 提供更详细的错误信息
                    const errorDetails = {
                        originalLength: original.length,
                        cleanLength: cleanJson.length,
                        firstChar: cleanJson.charCodeAt(0),
                        lastChar: cleanJson.charCodeAt(cleanJson.length - 1),
                        sample: cleanJson.substring(0, 50)
                    };
                    console.error('JSON解析完全失败，错误详情:', errorDetails);
                    throw new Error(`JSON数据解析失败，存档可能已损坏。错误: ${e.message}`);
                }
            }
            
            // 添加元数据到结果中
            result.importMetadata = metadata;
            
            return result;
            
        } catch (error) {
            console.error('解密过程中出错:', error);
            throw new Error('存档数据解密失败: ' + error.message);
        }
    }

    // 安全的Base64解码（备用方法）
    safeBase64Decode(str) {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
        let result = '';
        let i = 0;
        
        // 移除非Base64字符
        str = str.replace(/[^A-Za-z0-9+\/]/g, '');
        
        while (i < str.length) {
            const encoded1 = chars.indexOf(str.charAt(i++));
            const encoded2 = chars.indexOf(str.charAt(i++));
            const encoded3 = chars.indexOf(str.charAt(i++));
            const encoded4 = chars.indexOf(str.charAt(i++));
            
            const bitmap = (encoded1 << 18) | (encoded2 << 12) | (encoded3 << 6) | encoded4;
            
            result += String.fromCharCode((bitmap >> 16) & 255);
            if (encoded3 !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
            if (encoded4 !== 64) result += String.fromCharCode(bitmap & 255);
        }
        
        return result;
    }

    // 计算校验和
    calculateChecksum(data) {
        let hash = 0;
        for (let i = 0; i < data.length; i++) {
            const char = data.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // 转换为32位整数
        }
        return Math.abs(hash).toString(16);
    }

    // 验证存档数据（增强版）
    validateSaveData(data) {
        console.log('验证存档数据...', data);
        
        if (!data || typeof data !== 'object') {
            console.error('数据不是有效对象');
            return false;
        }
        
        // 检查必要字段
        const requiredFields = ['timestamp', 'version'];
        for (const field of requiredFields) {
            if (!data.hasOwnProperty(field)) {
                console.error(`缺少必要字段: ${field}`);
                return false;
            }
        }
        
        // 检查时间戳有效性
        if (typeof data.timestamp !== 'number' || data.timestamp <= 0) {
            console.error('无效的时间戳:', data.timestamp);
            return false;
        }
        
        // 检查版本信息
        if (typeof data.version !== 'string' || data.version.length === 0) {
            console.error('无效的版本信息:', data.version);
            return false;
        }
        
        // 检查数据结构（允许为空但必须是正确类型）
        if (data.settings && typeof data.settings !== 'object') {
            console.error('设置数据格式错误');
            return false;
        }
        
        if (data.achievements && !Array.isArray(data.achievements)) {
            console.error('成就数据格式错误');
            return false;
        }
        
        if (data.characterData && typeof data.characterData !== 'object') {
            console.error('角色数据格式错误');
            return false;
        }
        
        if (data.storyProgress && typeof data.storyProgress !== 'object') {
            console.error('故事进度数据格式错误');
            return false;
        }
        
        if (data.gameState && typeof data.gameState !== 'object') {
            console.error('游戏状态数据格式错误');
            return false;
        }
        
        console.log('存档数据验证通过');
        return true;
    }

    // 应用存档数据
    applySaveData(data) {
        // 恢复设置
        if (data.settings) {
            this.settings = { ...this.settings, ...data.settings };
            this.saveSettings();
            this.applySettings();
        }

        // 恢复游戏状态
        if (data.gameState && window.gameEngine) {
            window.gameEngine.loadGameState(data.gameState);
        }

        // 恢复成就
        if (data.achievements && window.achievementSystem) {
            window.achievementSystem.importAchievements(data.achievements);
        }

        // 恢复角色数据
        if (data.characterData && window.characterSystem) {
            window.characterSystem.loadCharacterData(data.characterData);
        }

        // 恢复故事进度
        if (data.storyProgress && window.storyManager) {
            window.storyManager.loadProgress(data.storyProgress);
        }
    }

    // 重置游戏
    resetGame() {
        const confirmed = confirm('确定要重置游戏吗？\n\n这将删除所有游戏进度、成就和设置，此操作不可撤销！');
        
        if (!confirmed) {
            this.showNotification('重置操作已取消');
            return;
        }

        // 二次确认
        const doubleConfirmed = confirm('最后确认：真的要删除所有数据吗？');
        if (!doubleConfirmed) {
            this.showNotification('重置操作已取消');
            return;
        }

        try {
            // 清除所有本地存储
            localStorage.clear();
            sessionStorage.clear();

            // 重置设置到默认值
            this.settings = {
                textSpeed: 3,
                soundEnabled: true,
                autoSave: true,
                highContrast: false,
                reducedMotion: false,
                fontSize: 'medium'
            };

            // 重置各个系统
            if (window.gameEngine) window.gameEngine.reset();
            if (window.achievementSystem) window.achievementSystem.reset();
            if (window.characterSystem) window.characterSystem.reset();
            if (window.storyManager) window.storyManager.reset();

            this.showNotification('游戏已重置，页面将刷新...');
            
            // 延迟刷新页面
            setTimeout(() => {
                window.location.reload();
            }, 2000);
            
        } catch (error) {
            console.error('重置游戏失败:', error);
            this.showNotification('重置失败，请手动刷新页面', 'error');
        }
    }

    // 应用所有设置
    applySettings() {
        this.updateSettingsUI();
        this.applyTextSpeed();
        this.applySoundSettings();
        this.applyHighContrast();
        this.applyReducedMotion();
        this.applyFontSize();
    }

    // 更新设置界面
    updateSettingsUI() {
        const textSpeed = document.getElementById('textSpeed');
        const textSpeedValue = document.getElementById('textSpeedValue');
        const soundEnabled = document.getElementById('soundEnabled');
        const autoSave = document.getElementById('autoSave');
        const highContrast = document.getElementById('highContrast');
        const reducedMotion = document.getElementById('reducedMotion');
        const fontSize = document.getElementById('fontSize');

        if (textSpeed) textSpeed.value = this.settings.textSpeed;
        if (textSpeedValue) textSpeedValue.textContent = this.settings.textSpeed;
        if (soundEnabled) soundEnabled.checked = this.settings.soundEnabled;
        if (autoSave) autoSave.checked = this.settings.autoSave;
        if (highContrast) highContrast.checked = this.settings.highContrast;
        if (reducedMotion) reducedMotion.checked = this.settings.reducedMotion;
        if (fontSize) fontSize.value = this.settings.fontSize;
    }

    // 保存设置
    saveSettings() {
        try {
            localStorage.setItem('timeEcho_settings', JSON.stringify(this.settings));
        } catch (error) {
            console.error('保存设置失败:', error);
        }
    }

    // 加载设置
    loadSettings() {
        try {
            const saved = localStorage.getItem('timeEcho_settings');
            if (saved) {
                this.settings = { ...this.settings, ...JSON.parse(saved) };
            }
        } catch (error) {
            console.error('加载设置失败:', error);
        }
    }

    // 显示通知
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${type === 'error' ? 'rgba(255, 107, 107, 0.9)' : 'rgba(0, 212, 255, 0.9)'};
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            z-index: 10000;
            font-weight: 500;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            animation: slideInRight 0.3s ease-out;
        `;
        notification.textContent = message;
        
        // 添加动画样式
        if (!document.getElementById('notification-styles')) {
            const style = document.createElement('style');
            style.id = 'notification-styles';
            style.textContent = `
                @keyframes slideInRight {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                @keyframes slideOutRight {
                    from { transform: translateX(0); opacity: 1; }
                    to { transform: translateX(100%); opacity: 0; }
                }
            `;
            document.head.appendChild(style);
        }
        
        document.body.appendChild(notification);
        
        // 3秒后移除
        setTimeout(() => {
            notification.style.animation = 'slideOutRight 0.3s ease-out';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    // 获取当前设置
    getSettings() {
        return { ...this.settings };
    }

    // 更新特定设置
    updateSetting(key, value) {
        if (this.settings.hasOwnProperty(key)) {
            this.settings[key] = value;
            this.saveSettings();
            this.applySettings();
        }
    }
}

// 创建全局实例
window.gameSettings = new GameSettings();